﻿using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebFormsIdentity
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (User.Identity.IsAuthenticated)
                {
                    LogoutButton.Visible = true;
                }
            }
        }

        public string GetUserMessage()
        {
            StringBuilder builder = new StringBuilder();
            if (Request.IsAuthenticated)
            {
                builder.AppendFormat("<h5 class='card-subtitle my-4'>当前用户已登录，登录名：{0}</h5>", HttpUtility.HtmlEncode(User.Identity.GetUserName()));
                ClaimsPrincipal user = Context.User as ClaimsPrincipal;
                if (user != null)
                {
                    builder.Append("<h6 class='card-subtitle my-3'>登录用户的 Claims 数据</h6>");
                    foreach (Claim claim in user.Claims)
                    {
                        builder.AppendFormat("<p class='card-text'><strong>{0}：</strong>{1}</p>", claim.Type, claim.Value);
                    }
                }
            }
            else
            {
                builder.AppendFormat("<h6 class='card-subtitle my-3'>当前用户还未登录！</h6>");
            }
            return builder.ToString();
        }

        protected void SignOut(object sender, EventArgs e)
        {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            authenticationManager.SignOut();
            Response.Redirect("~/Index.aspx");
        }
    }
}